/*
 * @Author: CodeHare
 * @Date: 2023-09-19 18:46:23
 * @LastEditors: CodeHare
 * @LastEditTime: 2023-12-02 09:31:01
 * @Description: 运行参数设置组件
 */
// ignore_for_file: unnecessary_overrides

import 'dart:async';
import 'package:dart_date/dart_date.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/rectangle_ems_romote_control/rectangle_operating_parameter_settings/rectangle_operating_parameter_settings_model.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class RectangleOperateParameterSettingController extends GetxController {
  RectangleOperateParameterSettingModel model =
      RectangleOperateParameterSettingModel();
  DeviceServices deviceServices = Get.find<DeviceServices>();

  /// 时间选择器部分
  late DateTime now;
  String? startHour;
  String? startMinute;
  String? endHour;
  String? endMinute;

  /// 时间选择器起始时间
  DateTime? initialStartDateTime;

  /// 时间选择器终止时间
  DateTime? initialEndDateTime;

  /// 设备 ID
  int? deviceId;

  /// 通过校验
  bool pass = true;

  /// 订阅 websocket
  UseSubsribe subsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? subscription;
  late StreamController<Map<String, dynamic>> streamController;
  late Stream<Map<String, dynamic>> broadcastStream;

  @override
  void onInit() {
    super.onInit();
    deviceId = Get.arguments['deviceId'];
    model.timeParameterMap = model.getTimeParameterMap();

    /// socket部分
    streamController = subsribe.start([deviceId!], true);
    broadcastStream = streamController.stream.asBroadcastStream();

    subscription = broadcastStream.listen((data) {
      model.socketMap.addEntries(data.entries);

      initPowerParameter();
      update();
    });
  }

  void initPowerParameter() {
    if (model.socketMap.isEmpty) return;

    model.socketMap.forEach((key, value) {
      if (key == 'handOpePcsPower') {
        model.manualPCSPower.text = value.toString();
      } else if (key == 'AtTheBeginningOfThePeriodOne') {
        model.timeParameterMap['1']!.startHour =
            addLeadingZero(value.toString());
      } else if (key == 'StartingPointOfTimePeriodOne') {
        model.timeParameterMap['1']!.startMinute =
            addLeadingZero(value.toString());
      } else if (key == 'AtTheEndOfThePeriodOne') {
        model.timeParameterMap['1']!.endHour = addLeadingZero(value.toString());
      } else if (key == 'PeriodEndMinuteOne') {
        model.timeParameterMap['1']!.endMinute =
            addLeadingZero(value.toString());
      } else if (key == 'PCSPeriodPowerOne') {
        model.time1PCSPower.text = value.toString();
      } else if (key == 'AtTheBeginningOfThePeriodTwo') {
        model.timeParameterMap['2']!.startHour =
            addLeadingZero(value.toString());
      } else if (key == 'StartingPointOfTimePeriodTwo') {
        model.timeParameterMap['2']!.startMinute =
            addLeadingZero(value.toString());
      } else if (key == 'AtTheEndOfThePeriodTwo') {
        model.timeParameterMap['2']!.endHour = addLeadingZero(value.toString());
      } else if (key == 'PeriodEndMinuteTwo') {
        model.timeParameterMap['2']!.endMinute =
            addLeadingZero(value.toString());
      } else if (key == 'PCSPeriodPowerTwo') {
        model.time2PCSPower.text = value.toString();
      } else if (key == 'AtTheBeginningOfThePeriodThree') {
        model.timeParameterMap['3']!.startHour =
            addLeadingZero(value.toString());
      } else if (key == 'StartingPointOfTimePeriodThree') {
        model.timeParameterMap['3']!.startMinute =
            addLeadingZero(value.toString());
      } else if (key == 'AtTheEndOfThePeriodThree') {
        model.timeParameterMap['3']!.endHour = addLeadingZero(value.toString());
      } else if (key == 'PeriodEndMinuteThree') {
        model.timeParameterMap['3']!.endMinute =
            addLeadingZero(value.toString());
      } else if (key == 'PCSPeriodPowerThree') {
        model.time3PCSPower.text = value.toString();
      } else if (key == 'AtTheBeginningOfThePeriodFour') {
        model.timeParameterMap['4']!.startHour =
            addLeadingZero(value.toString());
      } else if (key == 'StartingPointOfTimePeriodFour') {
        model.timeParameterMap['4']!.startMinute =
            addLeadingZero(value.toString());
      } else if (key == 'AtTheEndOfThePeriodFour') {
        model.timeParameterMap['4']!.endHour = addLeadingZero(value.toString());
      } else if (key == 'PeriodEndMinuteFour') {
        model.timeParameterMap['4']!.endMinute =
            addLeadingZero(value.toString());
      } else if (key == 'PCSPeriodPowerFour') {
        model.time4PCSPower.text = value.toString();
      } else if (key == 'AtTheBeginningOfThePeriodFive') {
        model.timeParameterMap['5']!.startHour =
            addLeadingZero(value.toString());
      } else if (key == 'StartingPointOfTimePeriodFive') {
        model.timeParameterMap['5']!.startMinute =
            addLeadingZero(value.toString());
      } else if (key == 'AtTheEndOfThePeriodFive') {
        model.timeParameterMap['5']!.endHour = addLeadingZero(value.toString());
      } else if (key == 'PeriodEndMinuteFive') {
        model.timeParameterMap['5']!.endMinute =
            addLeadingZero(value.toString());
      } else if (key == 'PCSPeriodPowerFive') {
        model.time5PCSPower.text = value.toString();
      }
    });

    update();
  }

  /// @description: 校验时间选择阶段
  /// @return {*}
  void validateTime(DateTime curStartTime, String key) {
    if (key == '1') return;

    // 前一时段
    var previous = model.timeParameterMap["${int.parse(key) - 1}"];
    // 前一时段结束时间
    DateTime previousEndTime = previous!.startDateTime;

    pass = previousEndTime.isBefore(curStartTime);
    if (!pass) {
      showError("时段$key必须晚于时段${int.parse(key) - 1}！");
    }
  }

  /// @description: 初始化当前时间
  /// @return {*}
  void initTime() {
    now = model.timeParameterMap['1']!.startDateTime;

    initialStartDateTime = initialEndDateTime = now;
    startHour = now.getHours.toString();
    startMinute = now.getMinutes.toString();
    endHour = now.getHours.toString();
    endMinute = now.getMinutes.toString();
  }

  /// @description: 单位数前置加零
  /// @return {*}
  String addLeadingZero(String? value) {
    if (value!.length == 1) {
      return '0$value';
    }

    return value;
  }

  /// @description: 赋值回填时间
  /// @return {*}
  void assignFormTime(
    DateTime startDateTime,
    DateTime endDateTime,
    String key,
  ) {
    if (!pass) return;

    model.timeParameterMap[key]!.startDateTime = startDateTime;
    model.timeParameterMap[key]!.endDateTime = endDateTime;

    startHour = model.timeParameterMap[key]!.startHour =
        addLeadingZero(startDateTime.getHours.toString());
    startMinute = model.timeParameterMap[key]!.startMinute =
        addLeadingZero(startDateTime.getMinutes.toString());
    endHour = model.timeParameterMap[key]!.endHour =
        addLeadingZero(endDateTime.getHours.toString());
    endMinute = model.timeParameterMap[key]!.endMinute =
        addLeadingZero(endDateTime.getMinutes.toString());

    /// 回填并将通道中数值进行更新
    if (key == '1') {
      streamController.add({
        'AtTheBeginningOfThePeriodOne': startHour,
        'StartingPointOfTimePeriodOne': startMinute,
        'AtTheEndOfThePeriodOne': endHour,
        'PeriodEndMinuteOne': endMinute,
      });
    } else if (key == '2') {
      streamController.add({
        'AtTheBeginningOfThePeriodTwo': startHour,
        'StartingPointOfTimePeriodTwo': startMinute,
        'AtTheEndOfThePeriodTwo': endHour,
        'PeriodEndMinuteTwo': endMinute,
      });
    } else if (key == '3') {
      streamController.add({
        'AtTheBeginningOfThePeriodThree': startHour,
        'StartingPointOfTimePeriodThree': startMinute,
        'AtTheEndOfThePeriodThree': endHour,
        'PeriodEndMinuteThree': endMinute,
      });
    } else if (key == '4') {
      streamController.add({
        'AtTheBeginningOfThePeriodFour': startHour,
        'StartingPointOfTimePeriodFour': startMinute,
        'AtTheEndOfThePeriodFour': endHour,
        'PeriodEndMinuteFour': endMinute,
      });
    } else {
      streamController.add({
        'AtTheBeginningOfThePeriodFive': startHour,
        'StartingPointOfTimePeriodFive': startMinute,
        'AtTheEndOfThePeriodFive': endHour,
        'PeriodEndMinuteFive': endMinute,
      });
    }

    update();
  }

  /// @description: 赋值回填时间选择器标题
  /// @return {*}
  void assignPickerTitle(String key) {
    if (model.timeParameterMap[key]!.startHour.isEmpty ||
        model.timeParameterMap[key]!.startMinute.isEmpty ||
        model.timeParameterMap[key]!.endHour.isEmpty ||
        model.timeParameterMap[key]!.endMinute.isEmpty) {
      model.pickerTitle =
          "${addLeadingZero(startHour)}:${addLeadingZero(startMinute)}-${addLeadingZero(endHour)}:${addLeadingZero(endMinute)}";
    } else {
      model.pickerTitle =
          "${model.timeParameterMap[key]!.startHour}:${model.timeParameterMap[key]!.startMinute} - ${model.timeParameterMap[key]!.endHour}:${model.timeParameterMap[key]!.endMinute}";
    }

    update();
  }

  /// @description: 赋值回填时间选择器中选中时间
  /// @return {*}
  void assignPickerTime(DateTime? startDateTime, DateTime? endDateTime) {
    initialStartDateTime = startDateTime;
    initialEndDateTime = endDateTime;

    update();
  }

  /// @description: 收集请求参数
  /// @return {*}
  Map<String, dynamic> collectParams() {
    deviceId = Get.arguments['deviceId'];

    var params = {
      "deviceId": deviceId,
      "serviceId": "pcsPowerSetting",
      "input": {
        "handOpePcsPower": model.manualPCSPower.text,
        "AtTheBeginningOfThePeriodOne": model.timeParameterMap['1']!.startHour,
        "StartingPointOfTimePeriodOne":
            model.timeParameterMap['1']!.startMinute,
        "AtTheEndOfThePeriodOne": model.timeParameterMap['1']!.endHour,
        "PeriodEndMinuteOne": model.timeParameterMap['1']!.endMinute,
        "PCSPeriodPowerOne": model.time1PCSPower.text,
        "AtTheBeginningOfThePeriodTwo": model.timeParameterMap['2']!.startHour,
        "StartingPointOfTimePeriodTwo":
            model.timeParameterMap['2']!.startMinute,
        "AtTheEndOfThePeriodTwo": model.timeParameterMap['2']!.endHour,
        "PeriodEndMinuteTwo": model.timeParameterMap['2']!.endMinute,
        "PCSPeriodPowerTwo": model.time2PCSPower.text,
        "AtTheBeginningOfThePeriodThree":
            model.timeParameterMap['3']!.startHour,
        "StartingPointOfTimePeriodThree":
            model.timeParameterMap['3']!.startMinute,
        "AtTheEndOfThePeriodThree": model.timeParameterMap['3']!.endHour,
        "PeriodEndMinuteThree": model.timeParameterMap['3']!.endMinute,
        "PCSPeriodPowerThree": model.time3PCSPower.text,
        "AtTheBeginningOfThePeriodFour": model.timeParameterMap['4']!.startHour,
        "StartingPointOfTimePeriodFour":
            model.timeParameterMap['4']!.startMinute,
        "AtTheEndOfThePeriodFour": model.timeParameterMap['4']!.endHour,
        "PeriodEndMinuteFour": model.timeParameterMap['4']!.endMinute,
        "PCSPeriodPowerFour": model.time4PCSPower.text,
        "AtTheBeginningOfThePeriodFive": model.timeParameterMap['5']!.startHour,
        "StartingPointOfTimePeriodFive":
            model.timeParameterMap['5']!.startMinute,
        "AtTheEndOfThePeriodFive": model.timeParameterMap['5']!.endHour,
        "PeriodEndMinuteFive": model.timeParameterMap['5']!.endMinute,
        "PCSPeriodPowerFive": model.time5PCSPower.text,
      },
    };

    return params;
  }

  /// @description: 下发指令接口
  /// @return {*}
  Future sendCommand(context) => Configs.httpClient.requestWithLoading(
        () async {
          var params = collectParams();
          await deviceServices.deviceRemoteSetting(params);
          FuncUtils.requestTipsDislog(context, "执行成功", true);
          update();
        },
        onError: (err) {
          FuncUtils.requestTipsDislog(context, "执行失败", false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          return true;
        },
      );

  @override
  void onClose() {
    super.onClose();

    /// 清除控制器
    model.manualPCSPower.clear();
    model.time1PCSPower.clear();
    model.time2PCSPower.clear();
    model.time3PCSPower.clear();
    model.time4PCSPower.clear();
    model.time5PCSPower.clear();

    /// 取消订阅
    subscription!.cancel();
    // subsribe.close();
  }
}
